<template>
  <div>
    <div class="table-page-search-wrapper">
      <div class="flex">
        <a-input class="inp" placeholder="请输入城市名称" v-model="inputVal" />
        <a-button type="primary" @click="search">查询</a-button>
      </div>
    </div>
    <div class="ts">
      绘制：鼠标左键点击及移动即可绘制图形 <br />
      结束绘制：鼠标左键双击即可结束绘制折线、多边形会自动闭合；<br />
      中断：绘制过程中点击取消键可中断该过程<br />
      编辑：可进入编辑状态，进行删除
    </div>
    <div class="mapWrap">
      <div id="toolControl">
        <a-button v-if="mode === 1" class="btn" type="primary" @click="handle('STOP')">取消</a-button>
        <a-button class="btn" type="primary" @click="handle('DRAW')">绘制</a-button>
        <a-button class="btn" type="primary" @click="handle('INTERACT')">编辑</a-button>
        <a-button v-if="mode === 2" class="btn" type="primary" @click="handle('DELETE')">删除</a-button>
        <div class="mts">当前状态：{{ mode === 1 ? '绘制模式' : '编辑模式' }}</div>
      </div>
      <div class="qqmap" id="qqmapCont"></div>
      <div class="lngTips"></div>
    </div>
  </div>
</template>

<script>
const statusLoading = {
  loading: true,
}
export default {
  components: {},
  data() {
    return {
      catList: [],
      form: this.$form.createForm(this),
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
      status: statusLoading,
      checkId: [], // 选择中ID
      qqmap: '',
      premarker: '',
      marker: '',
      inputVal: '',
      latlngCurrent: '',

      editor: null,
      mode: 1, // 1 绘制模式 2 交互模式
    }
  },
  props: {
    area: {
      type: Array,
      default() {
        return []
      },
    },
    zIndex: {
      type: Number,
      default: 1000,
    },
    value: {
      type: Boolean,
      default: true,
    },
    mapcenter: {
      type: String,
      default: '34.759666,113.648071',
    },
    oldmarker: {
      type: String,
      default: '34.759666,113.648071',
    },
    inputDefault: {
      type: String,
      default: '34.759666,113.648071',
    },
  },
  created() {},
  mounted() {
    this.$nextTick(() => {
      var that = this
      this.loadQQmap()
      window.onMapFileLoad = function () {
        that.createMap()
      }
    })
  },
  watch: {},
  methods: {
    search() {
      // 调用地址解析类
      var geocoder = new TMap.service.Geocoder({
        complete: (result) => {
          this.qqmap.setCenter(result.detail.location)
          this.qqmap.setZoom(12)
        },
      })

      var address = this.inputVal

      geocoder.getLocation({ address }).then((res) => {
        if (!res.status) {
          console.log('res.result.location,', res.result.location)
          this.qqmap.setCenter(res.result.location)
        }
      })
    },
    inputChange() {
      this.$emit('addr', this.inputVal) // 地图点击坐标 传递给父组件
    },
    loadQQmap() {
      var script = document.createElement('script')
      // 设置标签的type属性
      script.type = 'text/javascript'
      // 设置标签的链接地址
      script.src =
        'https://map.qq.com/api/gljs?libraries=tools,service&v=2.exp&callback=onMapFileLoad&key=OV7BZ-ZT3HP-6W3DE-LKHM3-RSYRV-ULFZV'
      // 添加标签到dom
      document.body.appendChild(script)
    },
    createMap() {
      const geometries = this.addOverlay()

      this.$nextTick(() => {
        this.qqmap = new TMap.Map('qqmapCont', {
          zoom: 12, // 设置地图缩放级别
          center: new TMap.LatLng(this.mapcenter.split(',')[0], this.mapcenter.split(',')[1]), // 设置地图中心点坐标
        })

        var polygon = new TMap.MultiPolygon({
          map: this.qqmap,
          styles: {
            highlight: new TMap.PolygonStyle({
              color: 'rgba(255, 255, 0, 0.6)',
            }),
          },
          geometries,
        })

        this.editor = new TMap.tools.GeometryEditor({
          // TMap.tools.GeometryEditor 文档地址：https://lbs.qq.com/webApi/javascriptGL/glDoc/glDocEditor
          map: this.qqmap, // 编辑器绑定的地图对象
          overlayList: [
            // 可编辑图层 文档地址：https://lbs.qq.com/webApi/javascriptGL/glDoc/glDocEditor#4
            {
              overlay: polygon,
              id: 'polygon',
            },
          ],
          actionMode: TMap.tools.constants.EDITOR_ACTION.DRAW, // 编辑器的工作模式
          activeOverlayId: 'polygon', // 激活图层
          selectable: true,
          snappable: true, // 开启吸附
        })

        // 监听删除、修改、拆分、合并完成事件
        const evtList = ['draw', 'delete', 'adjust']
        evtList.forEach((evtName) => {
          this.editor.on(evtName + '_complete', (geometry) => {
            this.$emit('ok', JSON.parse(JSON.stringify(polygon._rawGeometries)))
          })
        })

        if (geometries.length) {
          let { area } = this,
            lat = parseFloat(area[0][0][1].toFixed(6)),
            lng = parseFloat(area[0][0][0].toFixed(6))

          this.qqmap.setCenter({
            lat,
            lng,
          })
        }
      })
    },

    addOverlay() {
      let geometries = []
      this.area.forEach((el, i) => {
        let arr = []
        el.forEach((e) => {
          arr.push(new TMap.LatLng(e[1], e[0]))
        })

        geometries.push(arr)
      })

      geometries = geometries.map((el) => {
        return {
          paths: el,
        }
      })

      return geometries
    },

    onCancel() {
      this.$emit('update:value', false)
    },
    onOk() {
      this.$emit('onOk', this.latlngCurrent)
      this.$emit('update:value', false)
    },

    handle(type) {
      let { editor } = this
      switch (type) {
        case 'STOP':
          editor.stop()
          break

        case 'DRAW':
          this.mode = 1
          editor.setActionMode(2)
          break

        case 'INTERACT':
          this.mode = 2
          editor.setActionMode(1)
          break

        case 'DELETE':
          editor.delete()
          break
      }
    },
  },
}
</script>
<style lang="less" scoped>
.permission-form {
  /deep/ .permission-group {
    margin-top: 0;
    margin-bottom: 0;
  }
}
.title-but {
  margin-left: 6px;
}
.qqmap {
  width: 100%;
  height: 600px;
}
.mapWrap {
  position: relative;
  width: 100%;
  height: 500px;
  overflow: hidden;
  margin-top: 15px;
}
.lngTips {
  display: none;
  width: 255px;
  height: 60px;
  padding: 5px 7px;
  overflow: hidden;
  position: absolute;
  left: 0;
  top: 0;
  z-index: 123456;
  background: #ffffff;
  border-radius: 5px;
  line-height: 20px;
  box-shadow: #eeeeee 1px 1px 3px;
  border: #eeeeee 1px solid;
  font-size: 12px;
}

#toolControl {
  position: absolute;
  left: 0;
  right: 0;
  top: 1%;
  text-align: center;
  z-index: 1001;

  .btn {
    margin: 0 2px;
  }
}

.mts {
  color: #ff0000;
}

.flex {
  display: flex;

  .inp {
    margin-right: 20px;
  }
}
</style>
